package org.androidpush.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


import org.androidpush.R;
import org.androidpush.adapter.ChatMsgViewAdapter;
import org.androidpush.client.Constants;
import org.androidpush.client.LogUtil;
import org.androidpush.client.NotificationService;
import org.androidpush.client.ServiceManager;
import org.androidpush.greendao.ChatMsg;
import org.androidpush.greendao.ChatMsgDao;
import org.androidpush.greendao.UserFriend;
import org.androidpush.greendao.UserFriendDao;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huang on 2017/4/14 0014.
 */
public class ChatActivity extends Activity{

    private static final String LOGTAG = LogUtil
            .makeLogTag(ChatActivity.class);

    private String friendId = null, friendName, userId;
    private ChatMsgDao chatMsgDao;
    private UserFriendDao userFriendDao;
    private List<ChatMsg> chatMsgDatas;
    private ChatMsgViewAdapter msgAdapter;
    private TextView sendTV;
    private Button senBtn;
    private ListView chatLV;
    private ServiceManager serviceManager;
    private ChatMsgReceiver chatMsgReceiver;
    private  UserFriend userFriend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_chat);
        init();
        ConstantUtils.aetActionBar(this, friendName);
        initDate();
        serviceManager = new ServiceManager(ChatActivity.this);
        chatLV.setSelection(chatLV.getCount() - 1);
        senBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send();
            }
        });

        chatMsgReceiver = new ChatMsgReceiver();
        IntentFilter chatfilter = new IntentFilter();
        chatfilter.addAction(Constants.ACTION_SHOW_CHATMSG);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLICKED);
        chatfilter.addAction(Constants.ACTION_CHATMSG_CLEARED);
        registerReceiver(chatMsgReceiver, chatfilter);
    }

    private void init() {
        chatMsgDao = DBUtils.getChatMsgDao(this);
        userFriendDao = DBUtils.getUserFriendDao(this);
        chatMsgDatas = new ArrayList<>();
        sendTV = (TextView) findViewById(R.id.id_chat_edt);
        chatLV = (ListView) findViewById(R.id.id_chat_list);
        senBtn = (Button) findViewById(R.id.id_chat_btn);
        msgAdapter = new ChatMsgViewAdapter(this, chatMsgDatas);
        SharedPreferences sp = ChatActivity.this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_APPEND);
        userId = sp.getString(ConstantUtils.USER_ID, "");
        Intent intent = getIntent();
        friendId = intent.getStringExtra(ConstantUtils.FRIEND_ID);
        userFriend = userFriendDao.queryRaw("WHERE FRIEND_ID = ?",friendId).get(0);

        friendName = userFriend.getFriendName();
    }

    private void initDate() {
        List<ChatMsg> chatMsgList = chatMsgDao.queryRaw("WHERE USER_ID = ? AND FRIEND_ID = ? DESC DATE" , userId, friendId);
        for (ChatMsg chatMsg : chatMsgList) {
            chatMsgDatas.add(chatMsg);
        }
        if (chatMsgDatas.size() > 0) {
            msgAdapter = new ChatMsgViewAdapter(this, chatMsgDatas);
            chatLV.setAdapter(msgAdapter);
        }
    }

    private void send() {
        String contString = sendTV.getText().toString();
        if (contString.length() > 0) {
            ChatMsg entity = new ChatMsg();
            entity.setUserId(Long.parseLong(friendId));
            entity.setDate(ConstantUtils.getFormatDate());
            Log.d("Date", entity.getDate());
            entity.setMessage(contString);
            entity.setMsgtype(false);
            entity.setFriendId(Long.parseLong(friendId));
            entity.setFriendname(friendName);
            entity.setFriendImg(userFriend.getFriendImg());
            chatMsgDao.insertOrReplace(entity);
            chatMsgDatas.add(entity);
            msgAdapter.notifyDataSetChanged();
            chatLV.setSelection(chatLV.getCount() - 1);
            sendTV.setText("");
            serviceManager.sendChatMsg(entity.getUserId().toString(), entity.getDate(), entity.getMessage(), entity.getMsgtype());
        } else {
            ConstantUtils.logToast(this, getResources().getString(R.string.str_chat_conternt_notnull));
        }
    }

    public class ChatMsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d(LOGTAG+"Receiver", "ChatMsgReceiver.onReceive()...");
            String action = intent.getAction();
            Log.d(LOGTAG, "action=" + action);

            if (Constants.ACTION_SHOW_CHATMSG.equals(intent.getAction())) {
                ChatMsg chatMsg = new ChatMsg();
                String chatToUser = intent
                        .getStringExtra(Constants.CHATMSG_TOUSER);
                String chatFromUser = intent
                        .getStringExtra(Constants.CHATMSG_FROMUSER);
                String chatDate = intent
                        .getStringExtra(Constants.CHATMSG_DATE);
                String chatMessage = intent
                        .getStringExtra(Constants.CHATMSG_MESSAGE);
                String chatType = intent
                        .getStringExtra(Constants.CHATMSG_TYPE);
                Log.d(LOGTAG+"Receiver", "chatToUser=" + chatToUser);
                Log.d(LOGTAG+"Receiver", "chatFromUser=" + chatFromUser);
                Log.d(LOGTAG+"Receiver", "chatDate=" + chatDate);
                Log.d(LOGTAG+"Receiver", "chatMessage=" + chatMessage);
                Log.d(LOGTAG+"Receiver", "chatType=" + chatType);
                chatMsg.setUserId(Long.parseLong(chatToUser));
                chatMsg.setFriendId(Long.parseLong(chatFromUser));
                chatMsg.setMessage(chatMessage);
                chatMsg.setDate(chatDate);
                chatMsg.setMsgtype(Boolean.parseBoolean(chatType));

                if(userFriendDao==null) {
                    userFriendDao = DBUtils.getUserFriendDao(ChatActivity.this);
                }

                UserFriend userFriend = userFriendDao.queryRaw("WHERE FRIEND_ID = ?", chatFromUser).get(0);
                if (userFriend != null) {
                    chatMsg.setFriendImg(userFriend.getFriendImg());
                    friendName = userFriend.getFriendName();
                    chatMsgDatas.add(chatMsg);
                    msgAdapter.notifyDataSetChanged();
                    chatLV.setSelection(chatLV.getCount() - 1);
                    chatMsgDao.insertOrReplace(chatMsg);
                } else {
                    friendName = "@" + getResources().getString(R.string.app_name);
                }

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtils.closeDB();
        unregisterReceiver(chatMsgReceiver);
    }
}
